package homelesspartners.tests.client.model;

import homelesspartners.client.model.Gift;
import homelesspartners.client.model.Shelter;
import homelesspartners.client.model.ShoppingList;
import homelesspartners.client.model.Story;
import homelesspartners.server.Data;
import homelesspartners.server.DataException;
import homelesspartners.server.utils.ScriptRunner;

import java.util.ArrayList;
import java.util.Iterator;

import junit.framework.TestCase;
import ashbyutils.database.testing.JndiUnitTestHelper;


public class ShoppingListTest extends TestCase {

	private static Data data = null;

	protected void setUp() throws Exception {
		super.setUp();
		if (JndiUnitTestHelper.notInitialized()) {
			JndiUnitTestHelper.init("src/homelesspartners/server/DatabaseUnitTests.properties");
		}
		ScriptRunner.runScriptOption(5);
		data = new Data();
	}

	protected void tearDown() throws Exception {
		super.tearDown();
		data = null;
	}

	public void testGetShelters() throws DataException {
		
		// pledge a gift, get the list of gift pledges, add them to the shopping list
		data.recordPledge(1, 1);
		ArrayList gifts = data.getShoppingList(1);
		ShoppingList list = new ShoppingList();
		for (Iterator giftIter = gifts.iterator(); giftIter.hasNext();) {
			Gift gift = (Gift) giftIter.next();
			list.addGift(gift);
		}
		
		// the gifts should belong to 2 different shelters
		ArrayList shelters = list.getShelters();
		assertEquals(2, shelters.size());
		
		ArrayList finalGiftList = new ArrayList();
		ArrayList finalStoriesList = new ArrayList();
		// for each shelter in the shopping list
		for (Iterator sheltersIter = shelters.iterator(); sheltersIter.hasNext();) {
			Shelter shelter = (Shelter) sheltersIter.next();
			ArrayList stories = shelter.getStories();
			// for each story in the shelter
			for (Iterator storiesIter = stories.iterator(); storiesIter.hasNext();) {
				Story story = (Story) storiesIter.next();
				// confirm it's linked with the same shelter object that it belongs to and add it to the list
				assertEquals(shelter, story.getShelter());
				finalStoriesList.add(story);
				Gift[] giftsList = story.getGifts();
				// for each gift
				for (int x = 0; x < story.getGiftCount(); x++) {
					Gift gift = giftsList[x];
					// confirm it's linked properly and add it to the list
					assertEquals(story, gift.getStory());
					finalGiftList.add(gift);
				}
			}
		}
		// confirm the number of gifts returned is the same as the number looped through
		assertEquals(gifts.size(), finalGiftList.size());
		assertEquals(4, finalStoriesList.size());
	}
}
